//
// Created by bbnf on 09.06.2024.
//

#include "storage/file_storage/file_parser.h"

namespace TodoApp::Storage::FileStorage {

    FileParser::FileParser(std::filesystem::path path) {
        assert(path.is_absolute());
        m_path = path;
    }

    [[maybe_unused]] TxtFileParser::TxtFileParser([[maybe_unused]] std::filesystem::path path) : FileParser(path) {
        LOG_LEVEL(LOG_LEVEL_TRACE);
    }

    auto TxtFileParser::parse() -> std::vector<TodoDto> {
        namespace fs = std::filesystem;
        assert(fs::exists(path()));

        static const std::string sep = "||";
        std::string line;
        std::vector<TodoDto> todos;
        std::ifstream file(path());
        while (std::getline(file, line)) {
            LOG_TRACE(line);
            auto todo_line = explode(sep, line);
            assert(todo_line.size() >= 5);
            TodoDto dto;
            dto = TodoDto{
                    static_cast<bool>(std::atoi(todo_line[0].c_str())),
                    todo_line[1],
                    todo_line[2],
                    _atoi64(todo_line[4].c_str()),
                    static_cast<std::int8_t>(std::atoi(todo_line[3].c_str()))
            };
            todos.push_back(dto);
        }
        file.close();
        return todos;
    }

    auto TxtFileParser::explode(std::string separator, std::string line) const -> std::vector<std::string> {
        std::vector<std::string> exploded;
        for (auto it = 0; it < line.size(); it++) {
            int pos = line.find(separator, it);
            if (pos < 0) {
                exploded.push_back(line.substr(it));
                break;
            }
            int count = pos - it;
            exploded.push_back(line.substr(it, count));
            it = pos + separator.length() - 1;
        }
        return exploded;
    }


}  // namespace TodoApp::Storage::FileStorage
